import { activeAnalysis, pageCuesActive } from '@/services/api/api-cues-active';
import { searchTreeOrganization } from '@/services/api/api-cues-submit';
import { TinyArea } from '@ant-design/charts';
import { FileImageOutlined, PaperClipOutlined } from '@ant-design/icons';
import { ProCard, ProColumns, ProFormCascader } from '@ant-design/pro-components';
import ProTable, { ActionType } from '@ant-design/pro-table';
import { Cascader, Input, Space, Spin, Tag } from 'antd';
import { DefaultOptionType } from 'antd/lib/select';
import moment from 'moment';
import React, { useEffect, useState } from 'react';
import { useAccess } from 'umi';
import OrganizationStatistics from '../../components/OrganizationStatistics';
import '../index.less';
import style from '../index.less';
import DetailsActive from './DetailsActive';
import ReceiptActive from "@/pages/cues/active/components/ReceiptActive";
interface AcitveTableProps {
  actionRef: ActionType;
  createdTimes: [];
  submitId:string;
}
const TableActive: React.FC<AcitveTableProps> = ({ actionRef, createdTimes,submitId }) => {
  const access = useAccess();

  const [width, setWidth] = useState(500);

  const [articleOrganizations, setArticleOrganizationState] = useState<any[]>([]);

  /**
   * 加载 单位 列表
   * @param key
   */
  const treeOrganizationData = async () => {
    try {
      const response = await searchTreeOrganization();
      if (response.code === 0) {
        setArticleOrganizationState(response.data);
      }
    } catch (error) {}
  };

  const [queryParam, setQueryParamState] = useState({});
  const [loading, setLoadingState] = useState(true);
  const [responsive, setResponsive] = useState(false);
  const [totalData, setTotalDataState] = useState<CuesActiveData.Analysis>();


  useEffect(() => {
    treeOrganizationData();
    analysisData();
    actionRef?.current?.reload();
  }, [createdTimes]);
  /**
   * 加载 单位 列表
   * @param key
   */
  const analysisData = async () => {
    try {
      const response = await activeAnalysis({ createdTimes });
      if (response.code === 0) {
        console.log(response.data);
        setLoadingState(false);
        setTotalDataState(response.data);
      }
    } catch (error) {}
  };

  const filter = (inputValue: string, path: DefaultOptionType[]) =>
    path.some(
      (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );

  const columns: ProColumns<CuesActiveData.ActivePage>[] = [
    {
      title: '报送线索',
      dataIndex: 'articleName',
      // copyable: true,
      search: false,
      ellipsis: true,
      width: '300px',
      align: 'center',
      key: 'articleName',
      render: (dom, record, _index, action) => {
        return (
          <div
            style={{
              textAlign: 'left',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
              overflow: 'hidden',
            }}
          >
            {record.isImage === 1 ? <FileImageOutlined /> : <></>}
            {record.isFile === 1 ? <PaperClipOutlined /> : <></>}
            <DetailsActive
              id={record.id}
              name={record.articleName}
              submitId={submitId}
              onRefurbish={() => {
                actionRef?.current?.reload();
              }}
            />
          </div>
        );
      },
    },
    {
      title: '单位',
      key: 'articleOrganizationAvatar',
      dataIndex: 'articleOrganizationAvatar',
      width: '180px',
      align: 'center',
      search: false,
      valueType: 'avatar',
      render: (dom, row) => (
        <div
          style={{
            textAlign: 'left',
            marginLeft: '24px',
          }}
        >
          {/* <Tag color={findTagColor(row.articleOrganizationTopName)}>
            {row.articleOrganizationTopName}
          </Tag> */}
          <span>{dom}</span>
          {row.articleOrganizationName}
        </div>
      ),
    },
    {
      title: '线索方向',
      dataIndex: 'articleIndustryName',
      key: 'articleIndustryName',
      width: '80px',
      align: 'center',
      search: false,
      render: (_, row) => {
        let industrys = row?.articleIndustrys;

        if (industrys.length > 2) {
          industrys = industrys.slice(0, 2);
          industrys.push({
            label: '...',
            value: '...',
          });
        }

        return (
          <Space size={[0, 8]} wrap>
            {industrys?.map(
              (item) =>
                // <Tag key={item.value}>{item.label}</Tag>
                item.label,
            )}
          </Space>
        );
      },
    },
    {
      title: '标签',
      dataIndex: 'articleLabels',
      key: 'articleLabels',
      width: '200px',
      align: 'center',
      search: false,
      render: (_, row) => {
        let labels = row?.articleLabels;

        if (labels.length > 2) {
          labels = labels.slice(0, 2);
          labels.push({
            label: '...',
            value: '...',
          });
        }
        return (
          <Space size={[0, 8]} wrap>
            {labels?.map((item) => (
              <Tag key={item.value}>{item.label}</Tag>
            ))}
          </Space>
        );
      },
    },
    {
      title: '新闻联络人',
      dataIndex: 'articleAccountName',
      // copyable: true,
      ellipsis: true,
      search: false,
      width: '100px',
      align: 'center',
      key: 'articleAccountName',
    },
    // {
    //   title: '阅读情况',
    //   hideInSearch: true,
    //   hideInTable: !access.线索征集x配置x管理员,
    //   dataIndex: 'receipt',
    //   key: 'receipt',
    //   valueType: 'avatar',
    //   width: '80px',
    //   align: 'center',
    //   search: false,
    //   render: (dom, record) => {
    //     return <ReceiptActive id={record.id} receipt={record.receipt} />;
    //   },
    // },
    {
      title: '浏览次数',
      hideInSearch: true,
      hideInTable: !access.线索征集x配置x管理员,
      dataIndex: 'receipt',
      key: 'receipt',
      valueType: 'avatar',
      width: '80px',
      align: 'center',
      search: false,
      render: (dom, record) => {
        return <ReceiptActive id={record.id} receipt={record.readCount} />;
      },
    },
    {
      title: '新闻刊播',
      dataIndex: 'ddd',
      key: 'ddd',
      width: '120px',
      align: 'center',
      search: false,
      render: (dom, record) => {
        return <>无</>;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      width: '120px',
      align: 'center',
      search: false,
    },
    {
      title: '报送日期',
      dataIndex: 'createdTimes',
      key: 'createdTimes',
      valueType: 'dateRange',
      hideInTable: true,
      fieldProps: {
        allowClear: true,
        placeholder: ['开始日期', '结束日期'],
        format: 'YYYY-MM-DD',
        ranges: {
          今日: [moment(), moment()],
          本月: [moment().startOf('month'), moment().endOf('month')],
          上月: [
            moment().startOf('month').subtract(1, 'months'),
            moment().endOf('month').subtract(1, 'months'),
          ],
          最近7天: [moment().subtract(6, 'days'), moment()],
          最近60天: [moment().subtract(59, 'days'), moment()],
          最近90天: [moment().subtract(89, 'days'), moment()],
        },
      },
    },
  ];

  return (
    <div>
      {(!access.线索征集x配置x提供者 || !access.线索征集x配置x区县提供者) && (
        <Spin spinning={loading} size="large">
          <ProCard
            headerBordered={false}
            bordered={false}
            direction={responsive ? 'column' : 'row'}
            ghost
          >
            <ProCard
              headerBordered={false}
              bordered={false}
              className={style.topic}
              split={responsive ? 'horizontal' : 'vertical'}
              style={{ padding: '10px 40px', width: '95%' }}
            >
              {access.线索征集x配置x媒体需求者 && (
                <div>
                  <h3>线索报送总量</h3>
                  <h2 style={{ color: '#467BE3' }}>{totalData?.countCountyActive} </h2>
                </div>
              )}
              {access.线索征集x配置x管理员 && (
                <OrganizationStatistics
                  trigger={
                    <div>
                      <h3>线索报送总量</h3>
                      <div style={{ display: 'flex' }}>
                        <ProCard
                          bordered={false}
                          split={responsive ? 'horizontal' : 'vertical'}
                          style={{ padding: '10px 40px', width: '90%' }}
                        >
                          <span>市级部门</span>
                          <h2 style={{ color: '#467BE3' }}>{totalData?.countMunicipalActive}</h2>
                        </ProCard>
                        <ProCard
                          bordered={false}
                          split={responsive ? 'horizontal' : 'vertical'}
                          style={{ padding: '10px 40px', width: '90%', marginLeft: 10 }}
                        >
                          <span>区县单位</span>
                          <h2 style={{ color: '#467BE3' }}>{totalData?.countCountyActive}</h2>
                        </ProCard>
                      </div>
                    </div>
                  }
                  createdTimes={createdTimes}
                />
              )}
            </ProCard>
            <ProCard
              bordered={false}
              className={style.submit}
              split={responsive ? 'horizontal' : 'vertical'}
              style={{ padding: '10px 40px', width: '95%' }}
            >
              {access.线索征集x配置x媒体需求者 && (
                <div>
                  <h3>报送单位总量</h3>
                  <h2 style={{ color: '#467BE3' }}>{totalData?.countCountyOrganization} </h2>
                </div>
              )}
              {access.线索征集x配置x管理员 && (
                <OrganizationStatistics
                  trigger={
                    <div>
                      <h3>报送单位总量</h3>
                      <div style={{ display: 'flex' }}>
                        <ProCard
                          bordered={false}
                          split={responsive ? 'horizontal' : 'vertical'}
                          style={{ padding: '10px 40px', width: '90%' }}
                        >
                          <span>市级部门</span>
                          <h2 style={{ color: '#467BE3' }}>
                            {totalData?.countMunicipalOrganization}
                          </h2>
                        </ProCard>
                        <ProCard
                          bordered={false}
                          split={responsive ? 'horizontal' : 'vertical'}
                          style={{ padding: '10px 40px', width: '90%', marginLeft: 10 }}
                        >
                          <span>区县单位</span>
                          <h2 style={{ color: '#467BE3' }}>{totalData?.countCountyOrganization}</h2>
                        </ProCard>
                      </div>
                    </div>
                  }
                  createdTimes={createdTimes}
                />
              )}
            </ProCard>
            <ProCard
              bordered={false}
              className={style.active}
              split={responsive ? 'horizontal' : 'vertical'}
              style={{ padding: '10px 40px', width: '95%' }}
            >
              <h3>7天报送分析</h3>
              <TinyArea
                style={{ height: 100 }}
                autoFit={true}
                smooth
                areaStyle={{
                  fill: 'l(270) 0:rgb(151 95 228 / 10%) 0.5:rgb(151 95 228 / 60%) 1:rgb(151 95 228)',
                }}
                line={{
                  color: '#975FE4',
                }}
                tooltip={{
                  customContent: (x, data) => {
                    if (x != null) {
                      return `${totalData?.cuesAnalysisLabelSos[x]?.label}: ${data[0].value}`;
                    } else {
                      return '';
                    }
                  },
                }}
                data={totalData ? totalData?.cuesAnalysisLabelSos.map((item) => item.value) : []}
                // data={[0, 0, 0, 0, 31]}
              />
            </ProCard>
          </ProCard>
        </Spin>
      )}

      <ProTable<CuesActiveData.ActivePage>
        columns={columns}
        actionRef={actionRef}
        request={async (params = {}) => {
          if (params.organizationIds) {
            const organizationParentIds: string[] = [];
            let organizationIds: string[] = [];

            params.organizationIds.forEach((item: string | any[]) => {
              if (item.length === 1) {
                organizationParentIds.push(item[0]);
              } else if (item.length > 1) {
                organizationIds.push(item[1]);
              }
            });
            organizationParentIds.forEach((id) => {
              const ids = articleOrganizations.find((item) => item.id === id).children;
              organizationIds = organizationIds.concat(ids.map((item: any) => item.id));
            });
            params.articleOrganizationIds = organizationIds;
          }

          const response = await pageCuesActive({
            createdSource: 1,
            createdTimes: createdTimes,
            ...queryParam,
            ...params,
          });

          return Promise.resolve({
            data: response.data.data,
            total: response.data.total,
            success: response.code === 0,
          });
        }}
        rowKey="id"
        dateFormatter="string"
        bordered
        search={false}
        sticky
        ghost
        pagination={{
          showQuickJumper: true,
          showSizeChanger: true,
          defaultPageSize: 20,
        }}
        headerTitle={
          <div
            style={{
              display: 'flex',
            }}
          >
            <Input.Search
              placeholder="查询标题"
              enterButton="搜索"
              allowClear
              style={{ maxWidth: 250, width: '100%' }}
              onChange={(e) => {
                setQueryParamState({ ...queryParam, articleName: e.target.value });
              }}
              onSearch={(value) => {
                actionRef.current?.reset();
              }}
            />
            <ProFormCascader
              hidden={access.线索征集x配置x提供者 || access.线索征集x配置x区县提供者}
              width="xl"
              className={style.assignStyle}
              name="assignOrganizationIds"
              placeholder="选择单位"
              style={{
                padding: '10px',
              }}
              formItemProps={{
                style: {
                  width: 500,
                  marginLeft: '18px',
                  marginBottom: '0px',
                },
              }}
              fieldProps={{
                options: articleOrganizations,
                showSearch: { filter },
                multiple: true,
                removeIcon: true,
                allowClear: true,
                maxTagCount: 'responsive',
                showCheckedStrategy: Cascader.SHOW_CHILD,
                // popupMatchSelectWidth: 400,
                // dropdownStyle: { height: 400, width: 400 , overflow: 'auto'},
                onChange(value, selectOptions) {
                  setQueryParamState({ ...queryParam, articleOrganizationIds: value });
                  actionRef.current?.reset();
                },
              }}
            />
          </div>
        }
        // toolbar={{
        //     filter: (
        //         <LightFilter
        //             onValuesChange={(value) => {
        //                 setQueryParamState(value);
        //                 actionRef?.current?.reset();
        //             }}
        //         >
        //             <ProFormDateRangePicker
        //                 name="createdTimes"
        //                 label="创建日期"
        //                 allowClear
        //                 fieldProps={{
        //                     allowClear: true,
        //                     placeholder: ['开始日期', '结束日期'],
        //                     format: 'YYYY-MM-DD',
        //                     ranges: {
        //                         今日: [moment(), moment()],
        //                         本月: [moment().startOf('month'), moment().endOf('month')],
        //                         上月: [
        //                             moment().startOf('month').subtract(1, 'months'),
        //                             moment().endOf('month').subtract(1, 'months'),
        //                         ],
        //                         最近7天: [moment().subtract(6, 'days'), moment()],
        //                         最近60天: [moment().subtract(59, 'days'), moment()],
        //                         最近90天: [moment().subtract(89, 'days'), moment()],
        //                     },
        //                 }}
        //             />
        //         </LightFilter>
        //     ),
        // }}
      />
    </div>
  );
};
export default TableActive;
